var url = require('url');
//所有的会话
var allSessions = {};
var socket;//服务器的socket
//初始化
exports.init = function (wss)
{
	console.log('websocket init');
	socket = wss;
	wss.on('connection', connection);
}

//根据id发送消息
exports.send = function (id,msg)
{
	let ws = allSessions[id];
	ws.send(msg);
}

//监听一个类型的消息
exports.onMessage = function (type,callback)
{
	for(let key in allSessions)
	{
		let ws = allSessions[key];
		ws.on('message',callback);
	}
}

exports.broadcast = function (msg)
{
	for(let key in allSessions)
	{
		let ws = allSessions[key];
		ws.send(msg);
	}
}

function connection(ws,req)
{
	console.log(req.headers);
	console.log(req.method);
	console.log(req.url);//websocket地址后面的内容，可以用来解析url参数
	//读取数据库，取出唯一id
	let params = url.parse(req.url,true).query;
	console.log(params);
	let login = "";
	login = params.login;
	console.log(login);
	let arr = login.split('@');
	console.log(arr);
	let acc = arr[0];
	let password = arr[1];
	let id;

	DB.query('baseInfo',{'acc':'111'},function (result)
	{
		console.log(result);
		let obj = result[0];
		if(obj.password == password)
		{
			console.log('登陆成功...');
			id = obj._id;
		}
		else//账号密码错误，返回错误码
		{
			// ws.close();
		}
	});

	allSessions[id] = ws;
	ws.on('message', function incoming(message) {
		console.log('received: %s', message);
	});
	ws.send('something');
}


